var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

// cloudmusic
var mysqlConfig1 = require('./config').mysqlConfig1;
// ip
var mysqlConfig2 = require('./config').mysqlConfig2;

var ipList = [];
var ipIndex = 0;
var proxy = '';

function changeIp() {
    if (ipIndex < ipList.length - 1) {
        ipIndex += 1;
    } else {
        ipIndex = 0;
    }
    setProxy();
}

function setProxy() {
    var item = ipList[ipIndex];
    console.log(item);

    var ip = item.ip;
    var port = item.port;

    proxy = `http://${ip}:${port}`;
    console.log('proxy');

    console.log(proxy);

}
function getIpList() {
    var connection1 = mysql.createConnection(mysqlConfig2);
    var query1 = 'select * from ip_table1 where (success_count>=5 and error_count/success_count<2 )';
    connection1.connect();
    connection1.query(query1, function (err, res) {
        if (err) {
            // console.log('query1 error');
            // setTimeout(() => {
            //     getIpList();
            // }, 3000);
        } else {
            ipList = res;
            if (ipList.length > 0) {
                console.log('ip count');
                console.log(ipList.length);

                setProxy();
                setInterval(() => {
                    changeIp();
                }, 300 * 1000);
                start();
            } else {
                console.log('no ip');

            }
        }
    });
    connection1.end();
}
getIpList();
function start() {
    // getSongList(1, 0);
    for (var i = 0; i < 10; i++) {
        var offset = 10 * i
        getSongList(1, offset);
    }
}

function getSongList(limit, offset) {
    var connection2 = mysql.createConnection(mysqlConfig1);
    connection2.connect();

    var query2 = `select * from song where (ISNULL(comment_updated) and comment_count>0) order by comment_count desc LIMIT ${limit} offset ${offset};`
    connection2.query(query2, function (err2, res2) {
        console.log(query2);

        if (err2) {
            console.log('query2 error');
            console.log(err2);


        } else {
            console.log('query2 success');
            console.log(res2);
            if (res2.length > 0) {
                var song = res2[0];
                var songId = song.id;
                getComment(songId);
                function getComment(songId) {
                    console.log('get comment count');

                    let url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_' + songId;
                    superagent.get(url)
                        .timeout(3000)
                        .proxy(proxy)
                        .end(function (err3, res3) {

                            console.log('http end');
                            console.log(proxy);
                            console.log(url);

                            if (err3) {
                                console.log(err3);
                                changeIp();
                                setTimeout(() => {
                                    getSongList(limit, offset);
                                }, 3000);
                            } else {
                                console.log('http success');
                                // console.log(res3.text);

                                let o = {};
                                try {
                                    o = JSON.parse(res3.text);
                                } catch (error) {
                                    getSongList(limit, offset);
                                }
                                let hotComments = [];
                                hotComments = o.hotComments;
                                if (typeof hotComments !== 'undefined') {
                                    if (hotComments.length > 0) {
                                        var list1 = o.hotComments.map(v => {
                                            var id = v.commentId;
                                            var content = v.content;
                                            var time = v.time;
                                            var likedCount = v.likedCount;
                                            // var songId = songId;

                                            return [id, content, time, likedCount, songId];
                                        });
                                        upload(list1);
                                    } else {
                                        console.log('没有热门评论');
                                        console.log();

                                        onUploaded(songId);
                                    }
                                } else {
                                    if (o.msg === '资源不存在') {
                                        getSongList(limit, offset + 1);
                                    }
                                    if (o.msg === 'Cheating') {
                                        console.log('cheating');
                                        setTimeout(() => {
                                            changeIp();
                                            getSongList(limit, offset);
                                        }, 3000);
                                    } else {
                                        getSongList(limit, offset + 1);
                                    }
                                }

                                function upload(commentList) {
                                    console.log(commentList);

                                    var connection3 = mysql.createConnection(mysqlConfig1);
                                    var query3 = 'insert ignore into comment (id,content,time,liked_count,song_id) values ?';
                                    connection3.connect();
                                    connection3.query(query3, [commentList], function (err, res) {
                                        if (err) {
                                            console.log('query3 err');
                                            console.log(err);
                                            getSongList(limit, offset);
                                        } else {
                                            console.log(res);
                                            onUploaded(songId);
                                        }
                                    });
                                    connection3.end();
                                }
                                function onUploaded(songId) {
                                    var connection4 = mysql.createConnection(mysqlConfig1);
                                    var query4 = 'update song set comment_updated=1 where id=' + songId;
                                    console.log(query4);
                                    connection4.connect();
                                    connection4.query(query4, function (err, res) {
                                        getSongList(limit, offset);
                                        if (err) {
                                            // 
                                        } else {
                                        }
                                    });
                                    connection4.end();
                                }
                                // console.log(item);
                                // console.log('msg');

                                // console.log(o.msg);

                                // if (o.msg === '资源不存在') {
                                //     commentCount = -1;

                                // }
                                // hotComments = p.hotComments;
                                // console.log(typeof commentCount);

                                // if (typeof commentCount === 'number') {
                                //     // console.log(item);
                                //     upload();
                                //     function upload() {
                                //         console.log('do upload');

                                //         var connection4 = mysql.createConnection(mysqlConfig1);
                                //         connection4.connect();

                                //         var query4 = `update song set comment_count=${commentCount} where id=${songId}`;
                                //         console.log(query4);

                                //         connection4.query(query4, function (err4, res4) {
                                //             if (err4) {
                                //                 console.log('query4 err');

                                //                 console.log(err4);

                                //             } else {
                                //                 console.log('query4 success');
                                //                 console.log(res4);
                                //                 getSongList(limit, offset);
                                //                 // connection4.destroy();
                                //                 // connection4.
                                //             }
                                //         });
                                //         connection4.end();
                                //     }
                                // } else {
                                //     if (o.msg === 'Cheating') {
                                //         console.log('cheating');
                                //         setTimeout(() => {
                                //             changeIp();
                                //             getSongList(limit, offset);
                                //         }, 3000);
                                //     } else {
                                //         getSongList(limit, offset + 1);
                                //     }
                                // }
                            }
                        })
                }
            } else {
                console.log('no song');

            }
        }
    });
    connection2.end();
}
